package com.endoc.agingtools.utils;

import android.bluetooth.BluetoothGattCharacteristic;
import android.content.Context;
import android.graphics.Color;
import android.os.Handler;
import android.util.Log;
import android.widget.TextView;

import androidx.recyclerview.widget.RecyclerView;

import com.endoc.agingtools.BitFieldUtils;
import com.endoc.agingtools.adapter.DeviceRecycleViewAdapter;
import com.endoc.agingtools.FinalStaticString;

import java.lang.ref.Reference;
import java.lang.ref.WeakReference;
import java.util.Calendar;
import java.util.List;
import java.util.UUID;

import cn.com.heaton.blelibrary.ble.Ble;
import cn.com.heaton.blelibrary.ble.callback.BleConnectCallback;
import cn.com.heaton.blelibrary.ble.callback.BleNotifyCallback;
import cn.com.heaton.blelibrary.ble.callback.BleWriteCallback;
import cn.com.heaton.blelibrary.ble.model.BleDevice;

public class BleUtils {

    public static void initBle(Context context){
        Ble.options().setLogTAG("agingTool")
                //.setLogBleExceptions(true)//设置是否输出打印蓝牙日志（非正式打包请设置为true，以便于调试）
                .setThrowBleException(true)//设置是否抛出蓝牙异常
                .setAutoConnect(true)//设置是否自动连接
                .setConnectFailedRetryCount(3)//连接失败重试时间
                .setConnectTimeout(10 * 1000)//设置连接超时时长（默认10*1000 ms）
                .setScanPeriod(10*1000)//设置扫描时长（默认10*1000 ms）
                .setMaxConnectNum(5)//默认是7
                .setUuidService(UUID.fromString("0000fff0-0000-1000-8000-00805f9b34fb"))//主服务的uuid
                .setUuidWriteCha(UUID.fromString("0000fff1-0000-1000-8000-00805f9b34fb"))//可写特征的uuid
                .create(context);
    }

    public static  void disConnecrDevice(BleDevice device){
        Ble.getInstance().disconnect(device);
    }

    public static  void setAutoConnecrDevice(BleDevice device,boolean isAutoConnect){
        Ble.getInstance().autoConnect(device,isAutoConnect);
    }

    public static void connectDevice(BleDevice devices, final RecyclerView.Adapter  kaweiRecycleViewAdapter,final RecyclerView.Adapter  deviceRecycleViewAdapter, final TextView textView){
        //可能导致内存泄露,此处用弱引用
        final Reference<RecyclerView.Adapter> kaweiAdapterReference = new WeakReference<RecyclerView.Adapter>(kaweiRecycleViewAdapter);
        final Reference<RecyclerView.Adapter> deviceAdapterReference = new WeakReference<RecyclerView.Adapter>(deviceRecycleViewAdapter);

        Ble.getInstance().connect(devices, new BleConnectCallback<BleDevice>() {
            @Override
            public void onConnectionChanged(BleDevice device) {
                //String openStatus = device.isConnected() ? "连接" : "断开";
                Log.d(FinalStaticString.TAG, device.getBleName()+"  "+device.isConnected());
                RecyclerView.Adapter kaweiAdapter = kaweiAdapterReference.get();
                if(kaweiAdapter!=null){
                    kaweiAdapter.notifyDataSetChanged();
                }

                RecyclerView.Adapter deviceAdapter = deviceAdapterReference.get();
                if(deviceAdapter!=null){
                    deviceAdapter.notifyDataSetChanged();
                }


             /*   if(deviceRecycleViewAdapter!=null){
                    deviceRecycleViewAdapter.notifyDataSetChanged();
                }*/
                if(textView!=null){
                    textView.setText(device.isConnected() ? "连接" : "断开");
                    textView.setTextColor(device.isConnected()? Color.parseColor("#FF5F51"):Color.parseColor("#323232"));
                }
            }

            @Override
            public void onReady(final BleDevice device) {
                super.onReady(device);
                Ble.getInstance().enableNotify(device, true, new BleNotifyCallback<BleDevice>() {

                    @Override
                    public void onChanged(BleDevice device, BluetoothGattCharacteristic characteristic) {
                        //获取发过来的数据
                        byte[] value = characteristic.getValue();
                        switch (value[3]){
                            case 0x20://绑定
                                Log.d(FinalStaticString.TAG,device.getBleName()+"设备绑定成功");
                                break;
                            case 0x2://启动
                                Log.d(FinalStaticString.TAG,device.getBleName()+"设备启动成功");
                                break;
                            case 0x3://停止
                                Log.d(FinalStaticString.TAG,device.getBleName()+"设备停止成功");
                                break;
                            default:
                                Log.d(FinalStaticString.TAG,device.getBleName()+"收到数据"+value[3]);
                                break;
                        }
                    }
                });

                //一秒钟后才发送
                new Handler().postDelayed(new Runnable() {
                    @Override
                    public void run() {
                        //发送绑定操作
                        byte[] accountBytes = BitFieldUtils.biteFieldToByteArray("13612874251");
                        byte[] bindData = {0x20, accountBytes[0], accountBytes[1], accountBytes[2], accountBytes[3], accountBytes[4], accountBytes[5], 0, 0, 0, 0, 0, 0};
                        writeData(device, bindData);
                    }
                }, 1000);
            }
        });
    }

    /**
     * 启动命令,给所有已经连接的设备发送启动命令
     */
    public static void sendStartCmd(){
        List<BleDevice> connectedDevices = Ble.getInstance().getConnectedDevices();
        Calendar mCalendar = Calendar.getInstance();
        byte[] startCmd = {2, 0, 0, 0, 0, 0, 0, 0, (byte) Integer.parseInt(("" + mCalendar.get(Calendar.YEAR)).substring(2)), (byte) (mCalendar.get(Calendar.MONTH) + 1), (byte) mCalendar.get(Calendar.DATE), (byte) mCalendar.get(Calendar.HOUR_OF_DAY), (byte) mCalendar.get(Calendar.MINUTE)};
        for (int i=0;i<connectedDevices.size();i++){
            writeData(connectedDevices.get(i),startCmd);
        }
    }

    /**
     * 停止命令,给所有已经连接的设备发送停止命令
     */
    public static void sendEndCmd(){
        List<BleDevice> connectedDevices = Ble.getInstance().getConnectedDevices();
        byte[] startCmd = {3, 0, 0, 0, 0, 0, 0, 0, 0, 0,0,0, 0};
        for (int i=0;i<connectedDevices.size();i++){
            writeData(connectedDevices.get(i),startCmd);
        }
    }



    public static void writeData(BleDevice device, byte data[]) {
        if (device != null) {//add 2019/12/2 在没连接设备的情况下,device为空,会导致app崩溃
            //device.writeData(sendData(data));

            Ble.getInstance().write(device, sendData(data), new BleWriteCallback<BleDevice>() {
                @Override
                public void onWriteSuccess(BleDevice device, BluetoothGattCharacteristic characteristic) {

                }

                @Override
                public void onWriteFailed(BleDevice device, int failedCode) {
                    super.onWriteFailed(device, failedCode);
                }
            });
        }
    }

    public static byte[] sendData(byte data[]) {
        byte sendData[] = {0x7E, 0x12, (byte) 0xAA, 0x01, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x00, 0x7e};
        for (int i = 0; i < 13; i++) {
            sendData[3 + i] = data[i];
        }
        for (int j = 0; j < sendData.length - 2; j++) {
            sendData[16] += sendData[j];
        }
        sendData[16] += sendData[17];
        //Log.d(TAG,"sendData=="+bytesToHexString(sendData,sendData.length));
        return sendData;
    }
}
